<template>
  <div class="message" :class="{ 'message-me': message.isMe }">
    <el-avatar :size="36" :src="message.isMe ? userStore.userInfo.avatar || defaultAvatar : friendAvatar"
      class="message-avatar" />

    <div class="message-content">
      <div v-if="showName" class="message-name">{{ message.name }}</div>

      <!-- 文字消息 -->
      <div v-if="message.type == 'text'" class="message-bubble">
        <div class="message-text">{{ message.content }}</div>
      </div>

      <!-- 图片消息 -->
      <div v-else-if="message.type == 'image'" class="message-bubble">
        <el-image class="message-image" :src="message.content" :preview-src-list="[message.content]" fit="cover"
          hide-on-click-modal />
      </div>

      <!-- 文件消息 -->
      <div v-else-if="message.type == 'file'" class="message-bubble message-file">
        <div class="file-icon">
          <el-icon :size="24">
            <Document />
          </el-icon>
        </div>
        <div class="file-info">
          <div class="file-name">{{ message.fileName }}</div>
          <div class="file-size">{{ formatFileSize(message.fileSize) }}</div>
        </div>
        <el-button type="text" size="small" @click="downloadFile(message)">下载</el-button>
      </div>

      <!-- 语音消息 -->
      <div v-else-if="message.type == 'audio'" class="message-bubble message-audio" @click="playAudio(message)">
        <el-icon :size="20">
          <Headset />
        </el-icon>
        <div class="audio-duration">{{ message.duration }}″</div>
        <div class="audio-wave">
          <div v-for="i in 20" :key="i" class="wave-bar" :style="{ height: randomHeight() + 'px' }"></div>
        </div>
      </div>

      <!-- 通话消息 -->
      <div v-else-if="message.type == 'call'" class="message-bubble message-call">
        <el-icon :size="20" :color="message.callType == 'video' ? '#409EFF' : '#67C23A'">
          <component :is="message.callType == 'video' ? VideoCamera : Microphone" />
        </el-icon>
        <div class="call-info">
          <div>{{ message.callType == 'video' ? '视频通话' : '语音通话' }}</div>
          <div class="call-duration">{{ formatCallDuration(message) }}</div>
        </div>
      </div>

      <!-- 时间 -->
      <div class="message-time">
        {{ formatTime(message.time) }}
        <span v-if="message.isMe" class="message-status">
          <el-icon v-if="message.status == 'sending'" class="loading">
            <Loading />
          </el-icon>
          <el-icon v-else-if="message.status == 'sent'">
            <CircleCheck />
          </el-icon>
          <el-icon v-else-if="message.status == 'failed'" color="#F56C6C">
            <CircleClose />
          </el-icon>
        </span>
      </div>
    </div>

    <!-- 已读状态 -->
    <div v-if="message.isMe && isLastMessage" class="message-read">
      <span v-if="message.read">已读</span>
      <span v-else>未读</span>
    </div>
  </div>
</template>

<script setup>
import {
  Document,
  Loading,
  CircleCheck,
  CircleClose,
  VideoCamera,
  Microphone,
  Headset
} from '@element-plus/icons-vue'

import { useUserStore } from "@/stores/user";

const props = defineProps({
  message: {
    type: Object,
    required: true
  },
  friendAvatar: {
    type: Boolean,
    default: defaultAvatar
  },
  showName: {
    type: Boolean,
    default: false
  },
  isLastMessage: {
    type: Boolean,
    default: false
  },
})

const defaultAvatar = 'https://picsum.photos/id/237/200/300'
const userStore = useUserStore()

// 方法
const formatTime = (time) => {
  if (!time) return '';
  const now = new Date();
  const date = time instanceof Date ? time : new Date(time);

  // 如果是当天，只显示时间
  if (date.toDateString() === now.toDateString()) {
    return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  }

  // 如果是昨天，显示"昨天 + 时间"
  const yesterday = new Date(now);
  yesterday.setDate(yesterday.getDate() - 1);
  if (date.toDateString() === yesterday.toDateString()) {
    return `昨天 ${date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;
  }

  // 其他情况显示完整日期时间
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
}

const formatFileSize = (bytes) => {
  if (!bytes) return '0B'
  if (bytes < 1024) return bytes + 'B'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + 'KB'
  return (bytes / (1024 * 1024)).toFixed(1) + 'MB'
}

const formatCallDuration = (message) => {
  if (message.status === 'missed') return '未接听'
  if (!message.seconds) return ''
  const seconds = Math.floor(message.seconds)
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins}:${secs.toString().padStart(2, '0')}`
}

const randomHeight = () => Math.floor(Math.random() * 10) + 5

const playAudio = (message) => {
  if (message.type !== 'audio') return;

const audio = new Audio();
const url = message.content;

// 手动设置类型，提高兼容性
const isWebm = url.includes('.webm') || url.includes('webm');
const mimeType = isWebm ? 'audio/webm' : 'audio/wav';

if (Audio.prototype.canPlayType && !audio.canPlayType(mimeType)) {
  console.error('当前浏览器不支持该音频格式:', mimeType);
  return;
}

audio.src = url;
audio.play().catch(e => {
  console.error('播放失败:', e);
});
}

const downloadFile = (message) => {
  const link = document.createElement('a')
  link.href = message.content
  link.download = message.fileName || 'file'
  link.click()
}
</script>

<style scoped>
.message {
  display: flex;
  margin-bottom: 15px;
  position: relative;
}

.message-me {
  flex-direction: row-reverse;
}

.message-avatar {
  align-self: flex-end;
  margin: 0 10px 22px 0;
}

.message-me .message-avatar {
  margin: 0 0 22px 10px;
}

.message-content {
  max-width: 70%;
  display: flex;
  flex-direction: column;
}

.message-name {
  font-size: 12px;
  color: #999;
  margin-bottom: 2px;
  margin-left: 6px;
}

.message-bubble {
  position: relative;
  padding: 8px 12px;
  border-radius: 4px;
  background-color: #f5f5f5;
  word-break: break-word;
  line-height: 1.5;
}

.message-me .message-bubble {
  background-color: #95ec69;
  color: #000;
}

.message-image {
  max-width: 200px;
  max-height: 200px;
  border-radius: 4px;
  cursor: pointer;
}

.message-file {
  display: flex;
  align-items: center;
  width: 250px;
  padding: 10px;
}

.file-icon {
  margin-right: 10px;
  color: #409eff;
}

.file-info {
  flex: 1;
  overflow: hidden;
}

.file-name {
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-size {
  font-size: 12px;
  color: #999;
}

.message-audio {
  display: flex;
  align-items: center;
  width: 180px;
  padding: 10px;
  cursor: pointer;
}

.audio-duration {
  margin: 0 10px;
  font-size: 14px;
}

.audio-wave {
  display: flex;
  align-items: flex-end;
  height: 30px;
  gap: 2px;
}

.wave-bar {
  width: 2px;
  background-color: currentColor;
  border-radius: 1px;
}

.message-call {
  display: flex;
  align-items: center;
  padding: 10px;
}

.call-info {
  margin-left: 10px;
}

.call-duration {
  font-size: 12px;
  color: #999;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  display: flex;
  align-items: center;
}

.message-me .message-time {
  justify-content: flex-end;
}

.message-status {
  margin-left: 4px;
  display: inline-flex;
}

.loading {
  animation: rotating 1.5s linear infinite;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

.message-read {
  position: absolute;
  right: 10px;
  bottom: -16px;
  font-size: 12px;
  color: #999;
}
</style>